package cn.gok.oa.attendance;

import cn.gok.oa.attendance.entity.TbAttendance;
import cn.gok.oa.attendance.mapper.TbAttendanceMapper;
import cn.gok.oa.system.entity.TbUser;
import cn.gok.oa.system.mapper.TbDeptMapper;
import cn.gok.oa.system.mapper.TbUserMapper;
import cn.gok.oa.util.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class attendanceScheduleTask {
    @Autowired
    TbAttendanceMapper attendanceMapper;
    @Autowired
    TbUserMapper userMapper;
    @Autowired
    TbDeptMapper deptMapper;
    //3.添加定时任务
    @Scheduled(cron = "01 30 16 * * ?")
    private void configureTasks() throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());                   //放入Date类型数据
        int year = calendar.get(Calendar.YEAR);
        int month =calendar.get(Calendar.MONTH)+1;                   //获取月份
        int day = calendar.get(Calendar.DATE);
        List<TbUser> users = userMapper.selectList(null);
        //去除员工列表后，判断数据库里有没有当天记录，没有则自动生成缺勤记录
        for (TbUser user: users) {
            QueryWrapper<TbAttendance> queryWrapper = new QueryWrapper();
            queryWrapper.between("time", DateUtil.StringToDate(year + "-" + month + "-" + day + " 00:00:00"),
                    DateUtil.StringToDate(year + "-" + month + "-" + day + " 23:59:59"));
            queryWrapper.lambda().eq(TbAttendance::getUserId,user.getId());
            TbAttendance attendance = attendanceMapper.selectOne(queryWrapper);
            if (attendance == null){
                attendance = new TbAttendance();
                attendance.setUserId(user.getId());
                attendance.setDeptId(user.getDeptId());
                attendance.setAttendanceStatus(2);
                attendance.setType(0);
                attendanceMapper.insert(attendance);
            }
        }
    }
}

